<template>
  <div class="app-container bg-gray">
    <el-row class="box-1">
      <el-col :span="24">
        <el-card>
          <div class="header">
            <div>
              <el-button type="success" class="bg-green" icon="el-icon-circle-plus" @click="showDialog()">新增类型/范围</el-button>
            </div>
          </div>
          <el-table v-loading="tableLoading" :data="tableData" :max-height="tableMaxHeight" border highlight-current-row @sort-change="handleSortChange">
            <el-table-column prop="id" label="ID" width="90" header-align="center" align="center" sortable />
            <el-table-column prop="name" label="服务类型/范围" min-width="160" header-align="center" align="center"/>
            <el-table-column prop="class" label="类别Tag" min-width="260">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.class" :key="index" type="success" style="margin-right: 6px;">{{ item.name }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="isReceive" label="指定接单" width="140" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row['isReceive']==='1'" type="success">已开启</el-tag>
                <el-tag v-else type="info">已关闭</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="serverName" label="服务人员" width="160" header-align="center" align="center"/>
            <el-table-column prop="status" label="状态" width="160" header-align="center" align="center">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.status==='1'" type="success">已开启</el-tag>
                <el-tag v-else type="info">已关闭</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" header-align="center" align="center">
              <template slot-scope="scope">
                <el-button type="success" class="bg-green" size="small" icon="el-icon-edit" circle @click="showDialog(scope)" />
                <el-button type="danger" size="small" icon="el-icon-delete" circle @click="toDelete(scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="pageSize"
            :page-sizes="pageSizes"
            :total="total"
            class="pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"/>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :title="form.title" width="600px" class="dialog" center @close="resetDialog('form')">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="类型（范围）名称" prop="name">
          <el-input v-model="form.name"/>
        </el-form-item>
        <el-form-item label="工作人员" prop="serverId">
          <!--不包含离职人员-->
          <el-select v-model="form.serverId" placeholder="请选择工作人员" class="select" clearable filterable>
            <el-option v-for="item in adminList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否指定接单人员" prop="isReceive">
          <el-radio-group v-model="form.isReceive">
            <el-radio label="1">是</el-radio>
            <el-radio label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="1">开启</el-radio>
            <el-radio label="2">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类别Tag">
          <el-row v-for="(item, index) in form.class" :key="index">
            <el-input v-model="item.name" style="width: 70%;"/>
            <el-button v-if="index===form.class.length-1" type="primary" class="el-icon-plus" size="mini" circle @click="addFormClass"/>
            <el-button v-if="form.class.length!==1" type="danger" class="el-icon-minus" size="mini" circle @click="deleteFormClass(index)"/>
          </el-row>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog('form')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { handleSortChange, handleSizeChange, handleCurrentChange } from '@/utils/table'

export default {
  data() {
    return {
      // 分类id
      catId: '',
      // 服务人员列表
      adminList: [],

      // 弹出框相关数据
      dialogVisible: false,
      form: {
       class: [{name: ''}]
      },
      rules: {
        name: [{ required: true, message: '请输入标题', trigger: 'change' }],
        serverId: [{ required: true, message: '请选择工作人员', trigger: 'change' }]
      },

      // 表格相关数据
      tableMaxHeight: document.documentElement.clientHeight - 280,
      tableLoading: false,
      currentPage: 1,
      pageSize: this.$store.getters.userInfo.pageSize,
      pageSizes: [10, 20, 50, 100, 1000],
      total: 0,
      tableData: []
    }
  },

  created() {
    this.catId = this.$route.query.id;
    this.getData();
    this.getUsersList();
  },

  methods: {
    handleCurrentChange, handleSizeChange, handleSortChange,
    getData(order) {
      this.tableLoading = true
      order || (order = {})
      const url = 'newWork/type/getPageList'
      const data = {
        catId: this.catId,
        pageNo: this.currentPage,
        pageSize: this.pageSize
      }
      order.sortName && (data.sortName = order.sortName)
      order.sortOrder && (data.sortOrder = order.sortOrder)
      this.$store.dispatch('GetConnect', { url, data }).then(res => {
        this.tableData = res.data.rows;
        this.total = res.data.total;
        this.tableLoading = false;
      }).catch(e => {
        this.tableLoading = false;
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    /**
     *  获取系统用户列表
     *  接口:'user/all-list'
     */
    getUsersList() {
      const url = 'user/admin-list'
      this.$store.dispatch('GetConnect', { url }).then(res => {
        this.adminList = res.data['list'][0]['personnel'];
      }).catch(e => {
        this.$message.error(e.msg + ',请刷新或联系管理员')
      })
    },

    // 显示弹窗
    showDialog(scope) {
      if (scope) {
        this.form = scope.row;
        this.form.title = '编辑类型/范围'
        console.log(this.form);
      } else {
        this.form = {class: [{name: ''}]}
        this.form.title = '新增类型/范围';
      }
      this.dialogVisible = true;
    },

    addFormClass() {
      this.form.class.push({});
    },

    deleteFormClass(index) {
      this.form.class.splice(index, 1);
    },

    /**
     * 弹窗表单提交方法,通过判断有没有form_id执行添加或编辑操作
     * formName: form表单中ref的值,即表单名
     */
    submitDialog(formName) {
      this.$refs[formName].validate((valid) => { // 表单验证
        if (valid) {
          const url = this.form.id ? 'newWork/type/update' : 'newWork/type/create';
          const data = Object.assign({}, this.form);
          data.class = JSON.stringify(data.class);
          data.catId = this.catId;
          this.$store.dispatch('GetConnect', { url, data }).then(res => {
            this.dialogVisible = false;
            this.$message.success(res.msg);
            this.getData();
          }).catch(e => {
            this.$message.error(e.msg + ',请刷新或联系管理员!');
          })
        } else {
          this.$message.error('提交失败,请检查必填项');
        }
      })
    },
    resetDialog(formName) {
      this.$refs[formName].resetFields();
    },

    toDelete(row) {
      this.$confirm('此操作将删除该类型/范围, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const url = 'newWork/type/delete';
        const data = { id: row.id }
        this.$store.dispatch('GetConnect', { url, data }).then(res => {
          this.$message.success(res.msg);
          this.getData();
        }).catch(e => {
          this.$message.error(e.msg);
        })
      })
    }
  }
}
</script>

<style lang="scss" type="text/scss" scoped>
@import '../../../../styles/index.scss';
.box-1 {
  .header {
    @include flex-row(center, space-between);
    padding-bottom: 16px;
    flex-wrap: wrap;
    > div {
      @include flex-row(center, flex-start);
      flex-wrap: wrap;
      width: 100%;
    }
    .search-input {
      width: 240px;
    }
    .do-btn {
      @extend .bg-green;
      margin-left: 6px;
    }
  }
}
.el-tag {
  cursor: pointer;
}
</style>
